package com.luckku.boot.service;
import com.alibaba.fastjson.JSONObject;
import com.luckku.boot.mapper.GoodsMapper;
import com.luckku.boot.mapper.OrderMapper;
import com.luckku.boot.mapper.UserMapper;
import com.luckku.boot.model.entity.OrderInfo;
import com.luckku.boot.model.entity.User;
import com.luckku.boot.utils.SnowFlakeUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 徐柯
 * @Title:
 * @Package
 * @Description:
 * @date 2021/3/2221:06
 */
@Component
@Log4j2
public class PayCommonService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SnowFlakeUtil snowFlakeUtil;

    /**
     * 支付回调封装
     * @param jsonObject
     * @param transactionId
     * @param payMethod
     */
    public void payOrder(JSONObject jsonObject, String transactionId, String payMethod) {
        // 支付的订单号
        String orderId = jsonObject.getString("orderId");
        // 用户id
        String userId = jsonObject.getString("userId");
        // 支付的金额
        String money = jsonObject.getString("money");
        // 根据产品查询产品信息
        OrderInfo orderInfo = orderMapper.selectById(orderId);
        if (orderInfo == null) {
            log.info("支付订单已失效：{}", orderId);
            return;
        }
        User user = userMapper.selectById(userId);
        long getPoint = Long.parseLong(money) / 10;
        user.setPoint(user.getPoint()+getPoint);
        // 保存订单明细表
        orderInfo.setAliTradeNum(transactionId);
        orderInfo.setPayMethod(payMethod);
        orderInfo.setGetPoint(getPoint);
        orderInfo.setOrderState("1");
        orderMapper.updateById(orderInfo);
    }

    /**
     * 假装支付成功
     */
    public void fakePay(String orderId ) {

        // 根据产品查询产品信息
        OrderInfo orderInfo = orderMapper.selectById(orderId);
        if (orderInfo == null) {
            log.info("支付订单已失效：{}", orderId);
            return;
        }
        User user = userMapper.selectById(orderInfo.getUserId());
        long getPoint = orderInfo.getOrderCost() / 10;
        user.setPoint(user.getPoint()+getPoint);
        userMapper.updateById(user);
        // 保存订单明细表
        orderInfo.setAliTradeNum(String.valueOf(snowFlakeUtil.snowflakeId()));
        orderInfo.setPayMethod("1");
        orderInfo.setGetPoint(getPoint);
        orderInfo.setOrderState("1");
        orderInfo.setPayTime(new Date());
        orderMapper.updateById(orderInfo);
    }

}


